package com.emmmya.ocs.modules.system.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.emmmya.ocs.common.constant.RedisConstant;
import com.emmmya.ocs.common.utils.httpClient.RestTemplateUtil;
import com.emmmya.ocs.config.redis.RedisManager;
import com.emmmya.ocs.modules.system.entity.Menu;
import com.emmmya.ocs.modules.system.entity.Role;
import com.emmmya.ocs.modules.system.entity.UI.UIMenu;
import com.emmmya.ocs.modules.system.entity.User;
import com.emmmya.ocs.modules.system.service.MenuService;
import com.emmmya.ocs.modules.system.service.UserService;
import com.emmmya.ocs.modules.system.utils.UserUtils;
import com.emmmya.ocs.modules.system.vo.UserVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("admin")
@Api(tags = "后台管理")
public class AdminUIController {
    @Autowired
    UserUtils userUtils;

    @Autowired
    private UserService userService;
    @Autowired
    private RedisManager redisManager;
    @Autowired
    MenuService menuService;

    @Autowired
    RestTemplateUtil restTemplateUtil;

    @Autowired
    RestTemplate restTemplate;


    /**
     * 后台管理主页面
     *
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "admin/index";
    }

    /**
     * 后台管理主页2
     *
     * @param mv
     * @return
     */
    @RequestMapping("/index2")
    public String index2(Model mv) {
        //前端解析的menu类集合
        List<UIMenu> uiMenus = new ArrayList<>();
        //查询所有的一级目录
        List<Menu> menus = menuService.findByLevel(1);
        List<Menu> userMenu = new ArrayList<>();

        //查询当前用户的角色与可使用菜单
        User currentUser = userUtils.getCurrentUser();
        if (currentUser != null) {
            User user = userService.get(currentUser.getId());
            if (user != null) {
                List<Role> roles = user.getRoles();
                if (!roles.isEmpty()) {
                    roles.forEach(role -> {
                        userMenu.addAll(role.getMenus());
                    });
                }

                List<Long> userMenuIds = userMenu.stream().map(p -> p.getId()).collect(Collectors.toList());
                menus.forEach(e -> {
                    UIMenu uiMenu = new UIMenu();
                    uiMenu.setParentMenu(e);
                    List<Menu> subMenu = menuService.findByParentId(e.getId().intValue());
                    List<Menu> childrenMenu = subMenu.stream().sorted(Comparator.comparing(Menu::getSortNo)).filter(p -> userMenuIds.contains(p.getId())).collect(Collectors.toList());
                    if (childrenMenu != null && childrenMenu.size() > 0) {
                        uiMenu.setSubmenu(childrenMenu);
                        uiMenus.add(uiMenu);
                    }
                });
            }
            mv.addAttribute("menus", uiMenus);
        }
        mv.addAttribute("user", userUtils.getCurrentUser());
        return "admin2/index";
    }

    /**
     * 后台管理主页2
     *
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome(Model model) {
        //用户信息
        model.addAttribute("user",userUtils.getCurrentUser());
        //获取欢迎页基础数据
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //1.本日登录数
        UserVo userVo = new UserVo();
        userVo.setLastLoginDate(today);
        IPage<User> page = userVo.createPage();
        userService.getListByPage(page,userVo.createWrapper());
        long toDayLoginTotal = page.getTotal();
        model.addAttribute("toDayLoginTotal",toDayLoginTotal);
        //2.总注册数
        userVo.setLastLoginDate(null);
        //userVo.setS_date(today);
        IPage<User> page2 = userVo.createPage();
        userService.getListByPage(page2,userVo.createWrapper());
        long registerTotal = page2.getTotal();
        model.addAttribute("registerTotal",registerTotal);
        //3.今日注册数
        userVo.setLastLoginDate(null);
        userVo.setS_date(today);
        IPage<User> page3 = userVo.createPage();
        userService.getListByPage(page3,userVo.createWrapper());
        long toDayRegisterTotal = page3.getTotal();
        model.addAttribute("toDayRegisterTotal",toDayRegisterTotal);
//        //4.今日充值数
//        ResultEntityVo vo1 = new ResultEntityVo();
//        vo1.setStart(today);
//        vo1.setTradeStatus(Drt66Constant.SUCCESS);
//        IPage<ResultEntity> page1 = vo1.createPage();
//        resultEntityService.getListByPage(page1,vo1.createWrapper());
//        long rechargeSuccessTotal = page1.getTotal();
//        model.addAttribute("rechargeSuccessTotal",rechargeSuccessTotal);
//
//        //5.今日发放礼品数
//        GrantItemVo vo2 = new GrantItemVo();
//        vo2.setStart(today);
//        IPage<GrantItem> page4 = vo2.createPage();
//        grantItemService.getListByPage(page4,vo2.createWrapper());
//        long grantTotal = page4.getTotal();
//        model.addAttribute("grantTotal",grantTotal);
        //6.文章数

        //7.过期时间
        //7.1获取本机的机器码
        // String machineCode = HarinSystemUtils.getMachineCode();
        //7.2.发送http请求拿到该机的信息，包括公钥与生效时间、过期时间
//       // CustomerVo customerVo = new CustomerVo();
//        customerVo.setMachineCode(machineCode);
//        Result<Object> resultObj = restTemplateUtil.requestBeanPost("www.emmmya.com", "/customer/checkMe", customerVo, Result.class, restTemplate);
//        Integer code = resultObj.getCode();
//        if(code == 200){
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String customerStr = JSON.toJSONString(resultObj.getResult());
//            CustomerEntity customer = JSON.parseObject(customerStr, CustomerEntity.class);
//            //获取失效日期
//            Date expirationDate = new Date(customer.getExpirationTimestamp());
//            String expirationDateStr = format.format(expirationDate);
//            model.addAttribute("expirationDate",expirationDateStr);
//        }
        return "admin2/welcome";
    }

    /**
     * 后台管理主页2
     *
     * @return
     */
    @RequestMapping("adminAdd")
    public String adminAdd() {
        return "admin2/admin/admin-add";
    }




    /**
     * 用户列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/userManagement")
    public String userManagement(Model model) {
        User user = new User();
        // 排序方式，这里是以“createTime”为标准进行降序
        List<String> descList = new ArrayList<String>();
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");  //一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(0, 10, sort); // （当前页， 每页记录数， 排序方式）
        Page<User> userPage = userService.findAllByVoAndLimit(user, pageable);
        model.addAttribute("userPage", userPage);
        return "admin/user-list1";
    }

    @RequestMapping("/email-compose")
    public String emailConpose() {
        return "admin/app/email-compose";
    }


    /**
     * 编辑user页面
     * @param id user的id
     * @return
     */
    @GetMapping("/editUser")
    public ModelAndView editUser(@RequestParam("userId") Long id, ModelAndView model) {
        String userStr = (String) redisManager.get(RedisConstant.USER + id);
        User user = null;
        if (StringUtils.isEmpty(userStr)) {
            user = userService.get(id);
            String s = JSONObject.toJSONString(user);
        } else {
            user = JSONObject.parseObject(userStr, User.class);
        }
        model.addObject("user", user);
        model.setViewName("admin/edit-user");
        return model;
    }
}
